package me.zyl.hw.zylwatchface;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.graphics.Palette;
import android.support.wearable.watchface.CanvasWatchFaceService;
import android.support.wearable.watchface.WatchFaceService;
import android.support.wearable.watchface.WatchFaceStyle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.widget.Toast;

import org.ini4j.Config;
import org.ini4j.Profile;
import org.ini4j.Wini;

import java.io.File;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import me.zyl.tools.AppTools;
import me.zyl.tools.CommonUtils;
import me.zyl.tools.LunarCalendar;
import me.zyl.tools.StopWatch;
import me.zyl.tools.TextTools;

/**
 * Analog watch face with a ticking second hand. In ambient mode, the second hand isn't
 * shown. On devices with low-bit ambient mode, the hands are drawn without anti-aliasing in ambient
 * mode. The watch face is drawn with less contrast in mute mode.
 * <p>
 * Important Note: Because watch face apps do not have a default Activity in
 * their project, you will need to set your Configurations to
 * "Do not launch Activity" for both the Wear and/or Application modules. If you
 * are unsure how to do this, please review the "Run Starter project" section
 * in the Google Watch Face Code Lab:
 * https://codelabs.developers.google.com/codelabs/watchface/index.html#0
 */
public class MyWatchFace extends CanvasWatchFaceService {




    /*
     * Updates rate in milliseconds for interactive mode. We update once a second to advance the
     * second hand.
     */
    private static final long INTERACTIVE_UPDATE_RATE_MS = TimeUnit.SECONDS.toMillis(1);

    /**
     * Handler message id for updating the time periodically in interactive mode.
     */
    private static final int MSG_UPDATE_TIME = 0;

    @Override
    public Engine onCreateEngine() {
        return new Engine();
    }

    private static class EngineHandler extends Handler {
        private final WeakReference<MyWatchFace.Engine> mWeakReference;

        public EngineHandler(MyWatchFace.Engine reference) {
            mWeakReference = new WeakReference<>(reference);
        }

        @Override
        public void handleMessage(Message msg) {
            MyWatchFace.Engine engine = mWeakReference.get();
            if (engine != null) {
                switch (msg.what) {
                    case MSG_UPDATE_TIME:
                        engine.handleUpdateTimeMessage();
                        break;
                }
            }
        }
    }

    private class Engine extends CanvasWatchFaceService.Engine {

        //==============自定义变量(新)=================
        private int frameTop = 15;  //默认15帧每秒吧
        private CommonUtils mCommonUtils;
        private Paint mPaint;
        private boolean isTouch = false;   //是否有用户点击表盘
        private int touchTime = 0;  //1：单击，2：双击
        private float touchX = -1;
        private float touchY = -1;

        private String sdCard = Environment.getExternalStorageDirectory().getAbsolutePath();
        private String cName;  //当前加载表盘文件夹名
        private Map<String,Typeface> fonts = new HashMap<String,Typeface>();  //字体
        private Map<String,Bitmap> pics = new HashMap<String,Bitmap>();  //图片
        private List<String> pics_hide = new ArrayList<String>();  //隐藏显示用的图片
        private Map<String,StopWatch> stopWatches = new HashMap<String,StopWatch>();  //计时器数组
        private Map<String,Integer> REP_spins = new HashMap<>();  //反复旋转角度数组
        private Map<String,Integer> RVLT_REP_spins = new HashMap<>();  //反复旋转角度数组
        private Map<String,Float> spins = new HashMap<>();  //旋转角度数组
        private Map<String,Float> scales = new HashMap<>();  //缩放大小数组
        private Map<String,Float> REP_scales = new HashMap<>();  //反复缩放大小数组
        public Map<String,Float> RVLT_spins = new HashMap<String,Float>();  //旋转角度数组(公转)
        private Map<String,Integer> switchs = new HashMap<String,Integer>();  //切换数组
        private Map<String,Integer> framesjump = new HashMap<String,Integer>();  //{Spin}和{Switch}低于15帧的时候跳帧控制
        private Map<String,Integer> RVLT_framesjump = new HashMap<String,Integer>();  //{Spin}和{Switch}低于15帧的时候跳帧控制(公转)
        private String DayHour = "8";  //白天开始时间，默认8点
        private String NightHour = "20";  //夜晚开始时间，默认20点
        private String SecondType = "run";   //默认是跑针吧,walk是走针
        public int ScreenOn = -1;   //默认-1=系统默认,0是长亮吧，单位秒
        public int ScreenOnFlash = 60;   //单位分,长亮模式下几分钟后关屏1次。
        private List<Profile.Section> layers = new ArrayList<Profile.Section>();  //配置层
        private int showBattery100Level=0;   //电量%
        public boolean showWeather = false;  //是否显示天气
        private int mTemperature = 0;   //温度
        private int mWeatherIndex = 0;   //天气索引
        private String mWeatherDesc = "";   //天气描述
        public boolean showStep = false;  //是否显示步数
        private int mStep = 0;   //当前步数
        private boolean mBCharge = false;
        public boolean isDim = false;  //是否开启dim模式
        public boolean isDimRunning = false;  //是否正在运行dim模式
        private int dimBrightness = 50;   //dim模式亮度,默认50吧，因为系统最低亮度为60
        private int dimFlashTime = 1;  //单位分钟
        private int dimEnterTime = 15;  //几秒进入dim模式，单位秒
        //==============自定义变量(新)=================



//        private static final float HOUR_STROKE_WIDTH = 5f;
//        private static final float MINUTE_STROKE_WIDTH = 3f;
//        private static final float SECOND_TICK_STROKE_WIDTH = 2f;
//
//        private static final float CENTER_GAP_AND_CIRCLE_RADIUS = 4f;
//
//        private static final int SHADOW_RADIUS = 6;
        /* Handler to update the time once a second in interactive mode. */
        private final Handler mUpdateTimeHandler = new EngineHandler(this);
//        private Calendar mCalendar;
        private final BroadcastReceiver mTimeZoneReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
//                mCalendar.setTimeZone(TimeZone.getDefault());
                mCommonUtils.setTimeToNow();
                invalidate();
            }
        };
        private boolean mRegisteredTimeZoneReceiver = false;
        private boolean mMuteMode;
//        private float mCenterX;
//        private float mCenterY;
//        private float mSecondHandLength;
//        private float sMinuteHandLength;
//        private float sHourHandLength;
//        /* Colors for all hands (hour, minute, seconds, ticks) based on photo loaded. */
//        private int mWatchHandColor;
//        private int mWatchHandHighlightColor;
//        private int mWatchHandShadowColor;
//        private Paint mHourPaint;
//        private Paint mMinutePaint;
//        private Paint mSecondPaint;
//        private Paint mTickAndCirclePaint;
//        private Paint mBackgroundPaint;
//        private Bitmap mBackgroundBitmap;
//        private Bitmap mGrayBackgroundBitmap;
        private boolean mAmbient;
        private boolean mLowBitAmbient;
        private boolean mBurnInProtection;

        @Override
        public void onCreate(SurfaceHolder holder) {
            super.onCreate(holder);

            setWatchFaceStyle(new WatchFaceStyle.Builder(MyWatchFace.this)
                    .setAcceptsTapEvents(true)
                    .build());

//            mCalendar = Calendar.getInstance();

            mCommonUtils = CommonUtils.getInstance(getApplicationContext());

            mPaint = new Paint();
            loadMyWatchFace();  //加载自定义配置信息
//            initializeBackground();
//            initializeWatchFace();
        }

        private void loadMyWatchFace(){
            try {
                Log.i("zyltest",sdCard+"/zylWatchFace");
                File file = new File(sdCard+"/zylWatchFace");
                if (file.exists()) {
                    //这里开始加载自定义表盘,sdcard的读取权限先在手表设置里面手动开启，自动请求的后续再加吧
                    Log.i("zyltest","开始加载自定义表盘资源...");
                    file = new File(sdCard+"/zylWatchFace/config.ini");
                    if(file.exists()){
                        Wini wini = new Wini(file);
                        String dirName = wini.get("config","name");  //文件夹目录
                        cName = dirName;
                        //还有表盘文件夹也先用英文吧，中文支持问题后续解决。。目前在模拟器里面不行，可能是文件上传时候的问题也说不准
                        file = new File(sdCard+"/zylWatchFace/"+dirName);
                        if (file.exists()){
                            //这里先把表盘目录下的字体和图片加载到变量(内存)中,还是先不加载到内存吧，这样会导致加载很慢
//            File[] pics = file.listFiles();
//            for (File pic:pics){
//              if (pic.getName().contains("config.ini"))
//                continue;
//              else if (pic.isDirectory())
//                continue;
//              this.pics.put(pic.getName(),BitmapFactory.decodeFile(pic.getAbsolutePath()));
//            }
                            //字体也先不加载
//            file = new File(sdCard+"/zylWatchFace/"+dirName+"/fonts");
//            if (file.exists()&&file.isDirectory()){
//              File[] fonts = file.listFiles();
//              for (File font:fonts){
//                this.fonts.put("fonts/"+font.getName(),Typeface.createFromFile(font.getAbsolutePath()));
//              }
//            }
                            file = new File(sdCard+"/zylWatchFace/"+dirName+"/config.ini");
                            wini = new Wini();
                            Config cfg = new Config();
                            cfg.setMultiSection(true);
                            wini.setConfig(cfg);
                            wini.load(file);
                            //读取一些配置信息吧
                            String dayHour = wini.get("config","DayHour");
                            DayHour = "8";
                            if (dayHour!=null)
                                DayHour = dayHour;
                            String nightHour = wini.get("config","NightHour");
                            NightHour = "20";
                            if (nightHour!=null)
                                NightHour = nightHour;
                            String secondType = wini.get("config","SecondType");
                            SecondType = "run";
                            if (secondType!=null)
                                SecondType = secondType;
                            //dim模式下的亮屏亮度1-255,默认255，最高亮度，中=133，低=85
//                            String cBrightness = wini.get("config","DimBrightnessMax");
////              FashionFace.cBrightness = 255;   //这个先不处理
//                            if (cBrightness!=null){
//                                FashionFace.cBrightness = Integer.parseInt(cBrightness);
//                            }
//                            //dim模式下的亮度1-255
//                            String dimBrightness = wini.get("config","DimBrightness");
//                            this.dimBrightness = 50;
//                            if (dimBrightness!=null){
//                                this.dimBrightness = Integer.parseInt(dimBrightness);
//                            }
//                            //dim模式的刷新时间,分为单位
//                            String dimFlashTime = wini.get("config","DimFlashTime");
//                            this.dimFlashTime = 1;
//                            if (dimFlashTime!=null){
//                                this.dimFlashTime = Integer.parseInt(dimFlashTime);
//                            }
//                            if (initScreenOn==-99){
//                                //这里加个长亮吧
//                                String screenOn = wini.get("config","ScreenOn");
//                                ScreenOn = -1;
//                                if (screenOn!=null)
//                                    ScreenOn = Integer.parseInt(screenOn);
//                            }else{
//                                ScreenOn = initScreenOn;
//                            }
//                            //长亮模式下默认关屏亮屏一次，防止烧屏
//                            String ScreenOnFlash = wini.get("config","ScreenOnFlash");
//                            this.ScreenOnFlash = 60;
//                            if (ScreenOnFlash!=null){
//                                this.ScreenOnFlash = Integer.parseInt(ScreenOnFlash);
//                            }
//                            //几秒进入dim模式
//                            String dimEnterTime = wini.get("config","DimEnterTime");
//                            this.dimEnterTime = 15;
//                            if (dimEnterTime!=null){
//                                this.dimEnterTime = Integer.parseInt(dimEnterTime);
//                            }
//
//                            zylScreenOn();   //这里再加载一次吧
                            layers = wini.getAll("layer");  //读取所有图层信息
                            showWeather = false;
                            showStep = false;
                            isDim = false;  //默认不开启dim
                            isDimRunning = false;
//                            this.mHandler.removeMessages(15001); //这个也先remove掉吧
////              Log.d("zyltest","loadMyWatchFace saveScreenBrightness");
//                            FashionFace.changeMySelf = false;
//                            ZylUtils.saveScreenBrightness(mContext,FashionFace.cBrightness);  //这里也恢复一下亮度试试看
//              ZylUtils.changeAppBrightness(mContext,FashionFace.cBrightness);
                            for (Profile.Section layer:layers){
                                String content = layer.get("Content");
                                if (content.contains("{Weather.temp}"))
                                    showWeather = true;
                                if (content.contains("{Step}")||content.contains("{Step.Spin}")){
                                    showStep = true;
                                }
                                //这里判断一下是否开启dim模式
//                                if (ScreenOn==0){
//                                    //长亮情况下才执行dim的模式
//                                    String show = layer.get("Show");
//                                    if (show.contains("dim")){
//                                        isDim = true;
//                                    }
//                                }
                            }
//                            if (isDim){
//                                //如果有dim模式，那么15秒后触发dim吧
//                                this.mHandler.sendEmptyMessageDelayed(15001,this.dimEnterTime*1000);
//                            }
                        }else{
                            throw new Exception("zylWatchFace/"+dirName+"文件夹不存在");
                        }
                    }else{
                        throw new Exception("zylWatchFace/config.ini文件不存在");
                    }
                    Log.i("zyltest","成功加载自定义表盘资源...");
//                    return true;
                }
            }catch (Exception e){
                Log.i("zyltest","加载自定义表盘资源异常...");
                Toast.makeText(getApplicationContext(), "加载自定义表盘资源异常..."+e.getLocalizedMessage(), Toast.LENGTH_SHORT)
                        .show();
//                Toast.makeText(mContext,"加载自定义表盘资源异常..."+e.getLocalizedMessage(),Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }
        }

        private void initializeBackground() {
//            mBackgroundPaint = new Paint();
//            mBackgroundPaint.setColor(Color.BLACK);
//            mBackgroundBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.bg);

            /* Extracts colors from background image to improve watchface style. */
//            Palette.from(mBackgroundBitmap).generate(new Palette.PaletteAsyncListener() {
//                @Override
//                public void onGenerated(Palette palette) {
//                    if (palette != null) {
//                        mWatchHandHighlightColor = palette.getVibrantColor(Color.RED);
//                        mWatchHandColor = palette.getLightVibrantColor(Color.WHITE);
//                        mWatchHandShadowColor = palette.getDarkMutedColor(Color.BLACK);
//                        updateWatchHandStyle();
//                    }
//                }
//            });
        }

        private void initializeWatchFace() {
            /* Set defaults for colors */
//            mWatchHandColor = Color.WHITE;
//            mWatchHandHighlightColor = Color.RED;
//            mWatchHandShadowColor = Color.BLACK;

//            mHourPaint = new Paint();
//            mHourPaint.setColor(mWatchHandColor);
//            mHourPaint.setStrokeWidth(HOUR_STROKE_WIDTH);
//            mHourPaint.setAntiAlias(true);
//            mHourPaint.setStrokeCap(Paint.Cap.ROUND);
//            mHourPaint.setShadowLayer(SHADOW_RADIUS, 0, 0, mWatchHandShadowColor);
//
//            mMinutePaint = new Paint();
//            mMinutePaint.setColor(mWatchHandColor);
//            mMinutePaint.setStrokeWidth(MINUTE_STROKE_WIDTH);
//            mMinutePaint.setAntiAlias(true);
//            mMinutePaint.setStrokeCap(Paint.Cap.ROUND);
//            mMinutePaint.setShadowLayer(SHADOW_RADIUS, 0, 0, mWatchHandShadowColor);
//
//            mSecondPaint = new Paint();
//            mSecondPaint.setColor(mWatchHandHighlightColor);
//            mSecondPaint.setStrokeWidth(SECOND_TICK_STROKE_WIDTH);
//            mSecondPaint.setAntiAlias(true);
//            mSecondPaint.setStrokeCap(Paint.Cap.ROUND);
//            mSecondPaint.setShadowLayer(SHADOW_RADIUS, 0, 0, mWatchHandShadowColor);
//
//            mTickAndCirclePaint = new Paint();
//            mTickAndCirclePaint.setColor(mWatchHandColor);
//            mTickAndCirclePaint.setStrokeWidth(SECOND_TICK_STROKE_WIDTH);
//            mTickAndCirclePaint.setAntiAlias(true);
//            mTickAndCirclePaint.setStyle(Paint.Style.STROKE);
//            mTickAndCirclePaint.setShadowLayer(SHADOW_RADIUS, 0, 0, mWatchHandShadowColor);
        }

        @Override
        public void onDestroy() {
            mUpdateTimeHandler.removeMessages(MSG_UPDATE_TIME);
            super.onDestroy();
        }

        @Override
        public void onPropertiesChanged(Bundle properties) {
            super.onPropertiesChanged(properties);
            mLowBitAmbient = properties.getBoolean(PROPERTY_LOW_BIT_AMBIENT, false);
            mBurnInProtection = properties.getBoolean(PROPERTY_BURN_IN_PROTECTION, false);
        }

        @Override
        public void onTimeTick() {
            super.onTimeTick();
            invalidate();
        }

        @Override
        public void onAmbientModeChanged(boolean inAmbientMode) {
            super.onAmbientModeChanged(inAmbientMode);
            mAmbient = inAmbientMode;

//            updateWatchHandStyle();

            /* Check and trigger whether or not timer should be running (only in active mode). */
            updateTimer();
        }

        private void updateWatchHandStyle() {
            if (mAmbient) {
//                mHourPaint.setColor(Color.WHITE);
//                mMinutePaint.setColor(Color.WHITE);
//                mSecondPaint.setColor(Color.WHITE);
//                mTickAndCirclePaint.setColor(Color.WHITE);
//
//                mHourPaint.setAntiAlias(false);
//                mMinutePaint.setAntiAlias(false);
//                mSecondPaint.setAntiAlias(false);
//                mTickAndCirclePaint.setAntiAlias(false);
//
//                mHourPaint.clearShadowLayer();
//                mMinutePaint.clearShadowLayer();
//                mSecondPaint.clearShadowLayer();
//                mTickAndCirclePaint.clearShadowLayer();

            } else {
//                mHourPaint.setColor(mWatchHandColor);
//                mMinutePaint.setColor(mWatchHandColor);
//                mSecondPaint.setColor(mWatchHandHighlightColor);
//                mTickAndCirclePaint.setColor(mWatchHandColor);
//
//                mHourPaint.setAntiAlias(true);
//                mMinutePaint.setAntiAlias(true);
//                mSecondPaint.setAntiAlias(true);
//                mTickAndCirclePaint.setAntiAlias(true);
//
//                mHourPaint.setShadowLayer(SHADOW_RADIUS, 0, 0, mWatchHandShadowColor);
//                mMinutePaint.setShadowLayer(SHADOW_RADIUS, 0, 0, mWatchHandShadowColor);
//                mSecondPaint.setShadowLayer(SHADOW_RADIUS, 0, 0, mWatchHandShadowColor);
//                mTickAndCirclePaint.setShadowLayer(SHADOW_RADIUS, 0, 0, mWatchHandShadowColor);
            }
        }

        @Override
        public void onInterruptionFilterChanged(int interruptionFilter) {
            super.onInterruptionFilterChanged(interruptionFilter);
            boolean inMuteMode = (interruptionFilter == WatchFaceService.INTERRUPTION_FILTER_NONE);

            /* Dim display in mute mode. */
            if (mMuteMode != inMuteMode) {
                mMuteMode = inMuteMode;
//                mHourPaint.setAlpha(inMuteMode ? 100 : 255);
//                mMinutePaint.setAlpha(inMuteMode ? 100 : 255);
//                mSecondPaint.setAlpha(inMuteMode ? 80 : 255);
                invalidate();
            }
        }

        @Override
        public void onSurfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            super.onSurfaceChanged(holder, format, width, height);

            /*
             * Find the coordinates of the center point on the screen, and ignore the window
             * insets, so that, on round watches with a "chin", the watch face is centered on the
             * entire screen, not just the usable portion.
             */
//            mCenterX = width / 2f;
//            mCenterY = height / 2f;
//
//            /*
//             * Calculate lengths of different hands based on watch screen size.
//             */
//            mSecondHandLength = (float) (mCenterX * 0.875);
//            sMinuteHandLength = (float) (mCenterX * 0.75);
//            sHourHandLength = (float) (mCenterX * 0.5);
//
//
//            /* Scale loaded background image (more efficient) if surface dimensions change. */
//            float scale = ((float) width) / (float) mBackgroundBitmap.getWidth();
//
//            mBackgroundBitmap = Bitmap.createScaledBitmap(mBackgroundBitmap,
//                    (int) (mBackgroundBitmap.getWidth() * scale),
//                    (int) (mBackgroundBitmap.getHeight() * scale), true);

            /*
             * Create a gray version of the image only if it will look nice on the device in
             * ambient mode. That means we don't want devices that support burn-in
             * protection (slight movements in pixels, not great for images going all the way to
             * edges) and low ambient mode (degrades image quality).
             *
             * Also, if your watch face will know about all images ahead of time (users aren't
             * selecting their own photos for the watch face), it will be more
             * efficient to create a black/white version (png, etc.) and load that when you need it.
             */
            if (!mBurnInProtection && !mLowBitAmbient) {
//                initGrayBackgroundBitmap();
            }
        }

//        private void initGrayBackgroundBitmap() {
//            mGrayBackgroundBitmap = Bitmap.createBitmap(
//                    mBackgroundBitmap.getWidth(),
//                    mBackgroundBitmap.getHeight(),
//                    Bitmap.Config.ARGB_8888);
//            Canvas canvas = new Canvas(mGrayBackgroundBitmap);
//            Paint grayPaint = new Paint();
//            ColorMatrix colorMatrix = new ColorMatrix();
//            colorMatrix.setSaturation(0);
//            ColorMatrixColorFilter filter = new ColorMatrixColorFilter(colorMatrix);
//            grayPaint.setColorFilter(filter);
//            canvas.drawBitmap(mBackgroundBitmap, 0, 0, grayPaint);
//        }

        /**
         * Captures tap event (and tap type). The {@link WatchFaceService#TAP_TYPE_TAP} case can be
         * used for implementing specific logic to handle the gesture.
         */
        @Override
        public void onTapCommand(int tapType, int x, int y, long eventTime) {
            switch (tapType) {
                case TAP_TYPE_TOUCH:
                    // The user has started touching the screen.
//                    Toast.makeText(getApplicationContext(), "TOUCH", Toast.LENGTH_SHORT)
//                            .show();
                    break;
                case TAP_TYPE_TOUCH_CANCEL:
                    // The user has started a different gesture or otherwise cancelled the tap.
//                    Toast.makeText(getApplicationContext(), "TOUCH_CANCEL", Toast.LENGTH_SHORT)
//                            .show();
                    break;
                case TAP_TYPE_TAP:
                    touchTime = touchTime+1;
                    touchX = x;
                    touchY = y;
                    isTouch = true;
                    // The user has completed the tap gesture.
                    // TODO: Add code to handle the tap gesture.
//                    Toast.makeText(getApplicationContext(), "TAP", Toast.LENGTH_SHORT)
//                            .show();
                    break;
            }
            invalidate();
        }


        /**
         * 白天画图层
         * @param canvas
         */
        private void doDayDraw(Canvas canvas,String DayOrNight){
            Profile.Section e_layer=null;  //异常的时候用的
            int i=0;
            try{
                for (Profile.Section layer:layers){
                    e_layer = layer;
                    i = i+1;  //第几个图层
                    if (!layer.get("Show").contains(DayOrNight)){
                        continue;  //如果不是白天的图层就跳过
                    }
                    canvas.save();
                    String type = layer.get("Type");
                    float PosX = Float.parseFloat(layer.get("PosX"));
                    float PosY = Float.parseFloat(layer.get("PosY"));
                    int frame = 1;  //每秒帧数
                    String speed = layer.get("Speed");  //自转速度
                    if (speed!=null){
                        frame = Integer.parseInt(speed);
                    }
                    if (frame>60){//帧不能超过60
                        frame = 60;
                    }

                    int RVLT_frame=1;  //每秒帧数(公转)
                    String RVLT_speed = layer.get("RVLT_Speed");  //公转速度
                    if (RVLT_speed!=null){
                        RVLT_frame = Integer.parseInt(RVLT_speed);
                    }
                    if (RVLT_frame>60){//帧不能超过60
                        RVLT_frame = 60;
                    }

                    if (RVLT_frame>frameTop){
                        frameTop = RVLT_frame;
                    }
                    if(frame>frameTop){
                        frameTop = frame;
                    }

                    //这个先把它去掉吧。
                    if (frameTop<15){
                        frameTop = 15;
                    }


                    float scaleStep = 0;  //每次缩放的大小
                    String s_ScaleStep = layer.get("ScaleStep");
                    if (s_ScaleStep!=null)
                        scaleStep = Float.parseFloat(s_ScaleStep);
                    if (scaleStep<0)  //放大缩小不能小于0
                        scaleStep = 0;

                    float scaleResult = 0;  //缩放的最终大小
                    String s_ScaleResult = layer.get("ScaleResult");
                    if (s_ScaleResult!=null)
                        scaleResult = Float.parseFloat(s_ScaleResult);
                    if (scaleResult<0)  //放大缩小不能小于0
                        scaleResult = 0;


                    int spinAngle = 0;  //每次旋转角度或范围
                    String s_SpinAngle = layer.get("SpinAngle");
                    if (s_SpinAngle!=null)
                        spinAngle = Integer.parseInt(s_SpinAngle);
                    if (spinAngle>360)  //角度不能超过360度或-360度
                        spinAngle = 360;
                    if (spinAngle<-360)
                        spinAngle = -360;

                    int REP_spinAngle = 0;  //反覆旋转的最大角度或范围
                    String REP_s_SpinAngle = layer.get("REP_SpinAngle");
                    if (REP_s_SpinAngle!=null)
                        REP_spinAngle = Integer.parseInt(REP_s_SpinAngle);
                    if (REP_spinAngle>360)  //角度不能超过360度或-360度
                        REP_spinAngle = 360;
                    if (REP_spinAngle<-360)
                        REP_spinAngle = -360;

                    int RVLT_spinAngle = 0;  //每次旋转角度或范围(公转)
                    String RVLT_s_SpinAngle = layer.get("RVLT_SpinAngle");
                    if (RVLT_s_SpinAngle!=null)
                        RVLT_spinAngle = Integer.parseInt(RVLT_s_SpinAngle);
                    if (RVLT_spinAngle>360)  //角度不能超过360度或-360度
                        RVLT_spinAngle = 360;
                    if (RVLT_spinAngle<-360)
                        RVLT_spinAngle = -360;

                    int RVLT_REP_spinAngle = 0;  //反覆旋转的最大角度或范围（公转）
                    String RVLT_REP_s_SpinAngle = layer.get("RVLT_REP_SpinAngle");
                    if (RVLT_REP_s_SpinAngle!=null)
                        RVLT_REP_spinAngle = Integer.parseInt(RVLT_REP_s_SpinAngle);
                    if (RVLT_REP_spinAngle>360)  //角度不能超过360度或-360度
                        RVLT_REP_spinAngle = 360;
                    if (RVLT_REP_spinAngle<-360)
                        RVLT_REP_spinAngle = -360;

                    //文字对齐方式，或者指针的对齐方式
                    String align = layer.get("Align");
                    if (align==null)
                        align="left";
                    if (type.equals("text")){
                        //文字层
                        String text = layer.get("Content");
                        if (text.contains("{Battery}")){
                            //电量
                            text = text.replace("{Battery}",showBattery100Level+"");
                        }else if (text.contains("{Step}")){
                            //步数
                            text = text.replace("{Step}",mStep+"");
                        }else if (text.contains("{Weather.temp}")){
                            //温度
                            text = text.replace("{Weather.temp}",mTemperature+"");
                        }else if (text.contains("{Weather.desc}")){
                            //天气描述
                            text = text.replace("{Weather.desc}",mWeatherDesc+"");
                        }else if (text.contains("{Week.Cn}")){
                            //星期.中文
                            text = text.replace("{Week.Cn}",mCommonUtils.getDayNameOfWeek());
                        }else if (text.contains("{Week.En}")){
                            //星期.英文
                            text = text.replace("{Week.En}",mCommonUtils.getDayNameOfWeekEn());
                        }else if (text.contains("{Week.No}")){
                            //星期.数字
                            text = text.replace("{Week.No}",mCommonUtils.getDayNameOfWeekNo());
                        }else if (text.contains("{Month.Cn}")){
                            //月份.中文
                            text = text.replace("{Month.Cn}",mCommonUtils.getMonthChineseName());
                        }else if (text.contains("{Month.En}")){
                            //月份.英文
                            text = text.replace("{Month.En}",mCommonUtils.getMonthName());
                        }else if (text.contains("{Month.No}")){
                            //月份.数字
                            text = text.replace("{Month.No}",mCommonUtils.getMonthNo());
                        }else if(text.contains("{DaysMatter}")){
                            //倒数日
                            String s_date = layer.get("Date");
                            if (s_date==null){
                                return;  //空的就不显示了
                            }
                            if (s_date.length()==2){  //dd
                                Calendar setCal = Calendar.getInstance();
                                setCal.set(Calendar.DAY_OF_MONTH,Integer.parseInt(s_date));
                                Calendar cal = Calendar.getInstance();
                                if (setCal.get(Calendar.DAY_OF_MONTH)<cal.get(Calendar.DAY_OF_MONTH)){
                                    //如果倒数日到期了
                                    setCal.add(Calendar.MONTH,1);  //跳到下个月
                                }
                                long lDay = setCal.getTimeInMillis()-cal.getTimeInMillis();
                                long days = lDay/(1000*3600*24);
                                if (days==0&&lDay>86000000)   //误差校准
                                    days=1;
                                text = text.replace("{DaysMatter}",days+"");
                            }else if (s_date.length()==5){   //MM-dd
                                Calendar setCal = Calendar.getInstance();
                                setCal.set(Calendar.MONTH,Integer.parseInt(s_date.split("-")[0])-1);  //月份是从0开始算起
                                setCal.set(Calendar.DAY_OF_MONTH,Integer.parseInt(s_date.split("-")[1]));
                                Calendar cal = Calendar.getInstance();
                                if (setCal.get(Calendar.DAY_OF_YEAR)<cal.get(Calendar.DAY_OF_YEAR)){
                                    //如果倒数日到期了
                                    setCal.add(Calendar.YEAR,1);  //跳到下一年
                                }
                                long lDay = setCal.getTimeInMillis()-cal.getTimeInMillis();
                                long days = lDay/(1000*3600*24);
                                if (days==0&&lDay>86000000)   //误差校准
                                    days=1;
                                text = text.replace("{DaysMatter}",days+"");
                            }else if (s_date.length()==10){  //yyyy-MM-dd
                                Calendar setCal = Calendar.getInstance();
                                setCal.set(Calendar.YEAR,Integer.parseInt(s_date.split("-")[0]));
                                setCal.set(Calendar.MONTH,Integer.parseInt(s_date.split("-")[1])-1);  //月份是从0开始算起
                                setCal.set(Calendar.DAY_OF_MONTH,Integer.parseInt(s_date.split("-")[2]));
                                Calendar cal = Calendar.getInstance();
                                if (setCal.getTimeInMillis()<cal.getTimeInMillis()){
                                    //如果倒数日到期了
                                    return;  //直接不显示了
                                }
                                long lDay = setCal.getTimeInMillis()-cal.getTimeInMillis();
                                long days = lDay/(1000*3600*24);
                                if (days==0&&lDay>86000000)   //误差校准
                                    days=1;
                                text = text.replace("{DaysMatter}",days+"");
                            }else{
                                return;  //格式不正确
                            }
                        }else if (text.contains("{StopWatch}")){
                            //计时器,文字型的就固定为60分钟的量吧,格式固定为mm:ss:ms
                            String s_format = layer.get("Format");
                            if (s_format==null)
                                s_format = "{60m}:{00s}:{ms}";  //默认等于60分
                            int minute=-1;
                            int second=-1;
                            if(s_format.contains("m}")){
                                String temp = s_format.substring(0,s_format.indexOf("m}"));
                                temp = temp.substring(temp.lastIndexOf("{")+1,temp.length());
                                minute = Integer.parseInt(temp);
                            }else if(s_format.contains("s}")){
                                String temp = s_format.substring(0,s_format.indexOf("s}"));
                                temp = temp.substring(temp.lastIndexOf("{")+1,temp.length());
                                second = Integer.parseInt(temp);
                            }
                            StopWatch stopWatch;
                            //联动-关联同一个计时器
                            String s_refId=layer.get("RefId");
                            if (s_refId!=null){
                                if (stopWatches.containsKey("RefId"+s_refId)){
                                    stopWatch = stopWatches.get("RefId"+s_refId);
                                    if (second!=-1){
                                        stopWatch.setSecond(second);
                                    }
                                    if (minute!=-1){
                                        stopWatch.setMinute(minute);
                                    }
                                }else{
                                    stopWatch = new StopWatch(minute==-1?0:minute,second==-1?0:second);
                                    stopWatches.put("RefId"+s_refId,stopWatch);
                                }
                            }else{
                                if (stopWatches.containsKey("layer_"+i)){
                                    stopWatch = stopWatches.get("layer_"+i);
                                }else{
                                    stopWatch = new StopWatch(minute==-1?0:minute,second==-1?0:second);
                                    stopWatches.put("layer_"+i,stopWatch);
                                }
                            }
                            text = text.replace("{StopWatch}",stopWatch.getTimeText(s_format));
                            //点击的情况
                            String touch = layer.get("Touch");  //默认显示情况
                            boolean swWork = true;  //计时器是否响应点击事件
                            if (touch!=null&&touch.equals("show")){
                                if (pics_hide.contains(i+"")){
                                    swWork = false;
                                }
                            }else if (touch!=null&&touch.equals("hide")){
                                if (!pics_hide.contains(i+"")){
                                    swWork = false;
                                }
                            }
                            //取点击范围吧
                            Rect rect = new Rect();
                            mPaint.getTextBounds(text,0,text.length(),rect);
                            int offset = 10; //默认加个10吧
                            String s_touchTime = layer.get("TouchTime");
                            int i_touchTime = 1;
                            if (s_touchTime!=null){
                                i_touchTime = Integer.parseInt(s_touchTime);
                            }
                            if (swWork&&isTouch&&touchTime==i_touchTime){
                                int trX = (int)PosX-offset;
                                int trY = (int)PosY-offset;
                                int trW = rect.width()+offset*2;
                                int trH = rect.height()+offset*2;
                                String touchRange = layer.get("TouchRange");  //可以自定义位置
                                if (touchRange!=null){
                                    String[] touchRect = touchRange.split(",");
                                    trX = Integer.parseInt(touchRect[0]);
                                    trY = Integer.parseInt(touchRect[1]);
                                    trW = Integer.parseInt(touchRect[2]);
                                    trH = Integer.parseInt(touchRect[3]);
                                }
                                if (touchX>=trX&&touchX<=trX+trW
                                        &&touchY>=trY&&touchY<=trY+trH){
                                    //这里点击成功了
                                    if (stopWatch.getState()==0)
                                        stopWatch.start();
                                    else if (stopWatch.getState()==1)
                                        stopWatch.stop();
                                    else if (stopWatch.getState()==2)
                                        stopWatch.reset();
                                }
                            }
                        }else if(text.contains("{")&&text.contains("}")){
                            //日期格式
                            Date now = new Date();
                            //日期的加减
                            if (text.contains("-(")||text.contains("+(")){
                                now = TextTools.dateCompute(text,now);
                                //去掉+和-后面的内容
                                if (text.contains("-"))
                                    text = text.substring(0,text.indexOf("-"));
                                else if (text.contains("+"))
                                    text = text.substring(0,text.indexOf("+"));
                            }
                            String format = text.substring(text.indexOf("{")+1,text.indexOf("}"));
                            String date = new SimpleDateFormat(format, Locale.CHINA).format(now);
                            text = text.replace("{"+format+"}",date);
                        }
                        //字体
                        String font = layer.get("Font");
                        if (!fonts.containsKey(font)){
                            //如果字体还没有加载到内存中，就加载一下
                            fonts.put(font,Typeface.createFromFile(sdCard+"/zylWatchFace/"+cName+"/"+font));
                        }
                        mPaint.setTypeface(fonts.get(font));
                        mPaint.setTextSize(Float.parseFloat(layer.get("Size")));  //字体大小
                        mPaint.setColor(Color.parseColor(layer.get("Color")));  //字体颜色
                        //对齐方式
                        if (align.equals("center")){
                            PosX = PosX - (mPaint.measureText(text)/2);
                        }else if (align.equals("right")){
                            PosX = PosX - mPaint.measureText(text);
                        }
                        //旋转角度
                        canvas.translate(PosX,PosY);
                        canvas.rotate(spinAngle);  //旋转的角度
                        canvas.translate(-PosX,-PosY);
                        //这里判断是否显示吧
                        boolean canDraw = true;
                        String touch = layer.get("Touch");
                        String touchRange = layer.get("TouchRange");
                        String s_touchTime = layer.get("TouchTime");
                        String s_touchApp = layer.get("TouchApp");
                        String s_touchAppRange = layer.get("TouchAppRange");
                        int i_touchTime = 1;
                        if (s_touchTime!=null){
                            i_touchTime = Integer.parseInt(s_touchTime);
                        }
                        if (touch!=null&&touchRange!=null&&isTouch&&touchTime==i_touchTime){
                            String[] touchRect = touchRange.split(",");
                            int trX = Integer.parseInt(touchRect[0]);
                            int trY = Integer.parseInt(touchRect[1]);
                            int trW = Integer.parseInt(touchRect[2]);
                            int trH = Integer.parseInt(touchRect[3]);
                            if (touchX>=trX&&touchX<=trX+trW
                                    &&touchY>=trY&&touchY<=trY+trH){
                                //如果正好在图片所在范围，那么就触发一下显示/隐藏吧
                                if (touch.equals("show")){
                                    if (!pics_hide.contains(i+"")){
                                        pics_hide.add(i+"");
                                    }else{
                                        pics_hide.remove(i+"");
                                    }
                                }else if (touch.equals("hide")){
                                    if (pics_hide.contains(i+"")){
                                        pics_hide.remove(i+"");
                                    }else{
                                        pics_hide.add(i+"");
                                    }
                                }
                            }
                            //app点击范围分开来吧，默认跟着TouchRange
                            if (s_touchAppRange!=null){
                                touchRect = s_touchAppRange.split(",");
                                trX = Integer.parseInt(touchRect[0]);
                                trY = Integer.parseInt(touchRect[1]);
                                trW = Integer.parseInt(touchRect[2]);
                                trH = Integer.parseInt(touchRect[3]);
                            }
                            if (touchX>=trX&&touchX<=trX+trW
                                    &&touchY>=trY&&touchY<=trY+trH){
                                //如果正好在图片所在范围，那么就触发一下显示/隐藏吧
                                if (touch.equals("show")){
                                    if (!pics_hide.contains(i+"")){
//                                  pics_hide.add(i+"");
                                        //这里显示的时候点击成功了,调用app
                                        if (s_touchApp!=null)
                                            AppTools.startApp(getApplicationContext(),s_touchApp);
                                    }else{
//                                  pics_hide.remove(i+"");
                                    }
                                }else if (touch.equals("hide")){
                                    if (pics_hide.contains(i+"")){
//                                  pics_hide.remove(i+"");
                                    }else{
//                                  pics_hide.add(i+"");
                                        //这里显示的时候点击成功了,调用app
                                        if (s_touchApp!=null)
                                            AppTools.startApp(getApplicationContext(),s_touchApp);
                                    }
                                }else if (touch.equals("all")){  //不做显示隐藏触发
                                    //这里是指显示的时候点击成功了
                                    if (s_touchApp!=null)
                                        AppTools.startApp(getApplicationContext(),s_touchApp);
                                }
                            }
                        }
                        //没有点击的情况处理
                        if (touch!=null&&touch.equals("show")){
                            if (pics_hide.contains(i+"")){
                                canDraw = false;
                            }
                        }else if (touch!=null&&touch.equals("hide")){
                            if (!pics_hide.contains(i+"")){
                                canDraw = false;
                            }
                        }
                        if (canDraw)
                            canvas.drawText(text, PosX, PosY, this.mPaint);
                    }else if (type.equals("image")){
                        boolean canDraw = true;
                        String Content = layer.get("Content");
                        //图片层
                        String pic = "";
                        if (Content.contains("{Static}")){
                            pic = layer.get("Pic");

                            //加上缩放试一下
                            boolean needJump = false;
                            int jumpTop = 0;
                            int jumpIndex = 0;
                            if (frame<frameTop){
                                jumpTop = frameTop / frame;  //跳过几帧要用除
                                if (this.framesjump.containsKey(i+"")){
                                    jumpIndex = this.framesjump.get(i+"");
                                }
                                if (jumpIndex<jumpTop){
                                    this.framesjump.put(i+"",jumpIndex+1);
                                    needJump = true;
                                }else if (jumpIndex>=jumpTop){
                                    this.framesjump.remove(i+"");
                                }
                            }


                            float z_scaleStep = 1;   //初始化值为1，因为1是正常大小
                            if (this.scales.containsKey(i+"")){
                                z_scaleStep = this.scales.get(i+"");
                            }



                            if (scaleResult!=1){
                                float z_scaleResult = scaleResult;
                                if (this.REP_scales.containsKey(i+"")){
                                    z_scaleResult = this.REP_scales.get(i+"");
                                }
                                if (scaleResult<1){  //缩小
                                    if (z_scaleResult==scaleResult){  //状态是缩小的时候
                                        if (z_scaleStep<=z_scaleResult)
                                            this.REP_scales.put(i+"",0f);  //设为0表示要放大了
                                    }else if (z_scaleResult==0){  //状态是放大了
                                        scaleStep = -scaleStep;
                                        if (z_scaleStep>=1)
                                            this.REP_scales.put(i+"",scaleResult);  //状态设置成正向旋转
                                    }
                                }else if (scaleResult>1){ //放大
                                    if (z_scaleResult==scaleResult){  //状态是放大的时候
                                        if (z_scaleStep>=z_scaleResult)
                                            this.REP_scales.put(i+"",0f);  //设为0表示要缩小了
                                    }else if (z_scaleResult==0){  //状态是缩小了
                                        scaleStep = -scaleStep;
                                        if (z_scaleStep<=1)
                                            this.REP_scales.put(i+"",scaleResult);  //状态设置成正向旋转
                                    }
                                }
                            }



                            if(!needJump){
                                if (scaleResult<1){
                                    z_scaleStep = z_scaleStep - scaleStep;
                                }else if (scaleResult>1){
                                    z_scaleStep = z_scaleStep + scaleStep;
                                }

                            }
//                            if (z_scaleStep>scaleResult||z_scaleStep<0){
//                                z_scaleStep = z_scaleStep % scaleResult;
//                            }
//                            Log.i("zyltest",z_scaleStep+"");
                            this.scales.put(i+"",z_scaleStep);

                            if (!this.pics.containsKey(pic)){
                                //内存中没有图片的时候，先加载一下图片吧
                                this.pics.put(pic,BitmapFactory.decodeFile(sdCard+"/zylWatchFace/"+cName+"/"+pic));
                            }
                            float newX = PosX+this.pics.get(pic).getWidth()/2;
                            float newY = PosY+this.pics.get(pic).getHeight()/2;
                            canvas.scale(z_scaleStep,z_scaleStep,newX,newY);

                        }else if (Content.contains("{HourHand}")){
                            String[] pics = layer.get("Pic").split(",");
                            String picRight=null;
                            String picShadow=null;
                            if (pics.length==2){
                                //这个是有阴影
                                pic = pics[0];   //指针
                                picShadow = pics[1];  //阴影
                            }else if(pics.length>=3){
                                //这个是有阴影，指针还有左右两面
                                pic = pics[0];  //左面
                                picRight = pics[1];  //右面
                                picShadow = pics[2];  //阴影
                            }else{
                                pic = layer.get("Pic");
                            }
                            if (!this.pics.containsKey(pic)){
                                //内存中没有图片的时候，先加载一下图片吧
                                this.pics.put(pic,BitmapFactory.decodeFile(sdCard+"/zylWatchFace/"+cName+"/"+pic));
                            }
                            float newX = PosX+this.pics.get(pic).getWidth()/2;
                            float newY = PosY+this.pics.get(pic).getHeight()/2;
                            canvas.translate(newX,newY);
                            float angle=this.mCommonUtils.getHourSweepAngle() % 360;
                            canvas.rotate(angle);
                            canvas.translate(-newX,-newY);
                            //看看这里准备画一下阴影试一下
                            if (picShadow!=null){
                                int sPx = 10;  //阴影长(三角形斜边),默认10吧
                                String c_sPx = layer.get("Shadow");  //阴影长度
                                if (c_sPx!=null)
                                    sPx = Integer.parseInt(c_sPx);
                                int sunAngle = 0;  //太阳照射角度
                                String s_sunAngle = layer.get("SunAngle");
                                if (s_sunAngle!=null)
                                    sunAngle = Integer.parseInt(s_sunAngle);
                                double sCon =Math.toRadians(angle-sunAngle);
                                float sX = (float)(Math.sin(sCon)*sPx);  //x坐标
                                float sY = (float)(Math.cos(sCon)*sPx);  //y坐标
                                if (!this.pics.containsKey(picShadow)){
                                    //内存中没有图片的时候，先加载一下图片吧
                                    this.pics.put(picShadow,BitmapFactory.decodeFile(sdCard+"/zylWatchFace/"+cName+"/"+picShadow));
                                }
                                canvas.drawBitmap(this.pics.get(picShadow),PosX+sX, PosY+sY, null);
                                //这里处理指针的左右阴影
                                if(picRight!=null){
                                    if (sunAngle<0){
                                        if(angle>360+sunAngle&&angle<=360||angle>=0&&angle<360+sunAngle-180)
                                            pic = picRight;  //右阴影
                                    }else{
                                        if (angle>sunAngle&&angle<sunAngle+180)
                                            pic = picRight;  //右阴影
                                    }
                                }
                            }
                        }else if (Content.contains("{HourHand.24}")){
                            String[] pics = layer.get("Pic").split(",");
                            String picRight=null;
                            String picShadow=null;
                            if (pics.length==2){
                                //这个是有阴影
                                pic = pics[0];   //指针
                                picShadow = pics[1];  //阴影
                            }else if(pics.length>=3){
                                //这个是有阴影，指针还有左右两面
                                pic = pics[0];  //左面
                                picRight = pics[1];  //右面
                                picShadow = pics[2];  //阴影
                            }else{
                                pic = layer.get("Pic");
                            }
                            if (!this.pics.containsKey(pic)){
                                //内存中没有图片的时候，先加载一下图片吧
                                this.pics.put(pic,BitmapFactory.decodeFile(sdCard+"/zylWatchFace/"+cName+"/"+pic));
                            }
                            float newX = PosX+this.pics.get(pic).getWidth()/2;
                            float newY = PosY+this.pics.get(pic).getHeight()/2;
                            canvas.translate(newX,newY);
                            float angle=this.mCommonUtils.getHour24SweepAngle() % 360;
                            canvas.rotate(angle);
                            canvas.translate(-newX,-newY);
                            //看看这里准备画一下阴影试一下
                            if (picShadow!=null){
                                int sPx = 10;  //阴影长(三角形斜边),默认10吧
                                String c_sPx = layer.get("Shadow");  //阴影长度
                                if (c_sPx!=null)
                                    sPx = Integer.parseInt(c_sPx);
                                int sunAngle = 0;  //太阳照射角度
                                String s_sunAngle = layer.get("SunAngle");
                                if (s_sunAngle!=null)
                                    sunAngle = Integer.parseInt(s_sunAngle);
                                double sCon =Math.toRadians(angle-sunAngle);
                                float sX = (float)(Math.sin(sCon)*sPx);  //x坐标
                                float sY = (float)(Math.cos(sCon)*sPx);  //y坐标
                                if (!this.pics.containsKey(picShadow)){
                                    //内存中没有图片的时候，先加载一下图片吧
                                    this.pics.put(picShadow,BitmapFactory.decodeFile(sdCard+"/zylWatchFace/"+cName+"/"+picShadow));
                                }
                                canvas.drawBitmap(this.pics.get(picShadow),PosX+sX, PosY+sY, null);
                                //这里处理指针的左右阴影
                                if(picRight!=null){
                                    if (sunAngle<0){
                                        if(angle>360+sunAngle&&angle<=360||angle>=0&&angle<360+sunAngle-180)
                                            pic = picRight;  //右阴影
                                    }else{
                                        if (angle>sunAngle&&angle<sunAngle+180)
                                            pic = picRight;  //右阴影
                                    }
                                }
                            }
                        }else if (Content.contains("{MinuteHand}")){
                            String[] pics = layer.get("Pic").split(",");
                            String picRight=null;
                            String picShadow=null;
                            if (pics.length==2){
                                //这个是有阴影
                                pic = pics[0];   //指针
                                picShadow = pics[1];  //阴影
                            }else if(pics.length>=3){
                                //这个是有阴影，指针还有左右两面
                                pic = pics[0];  //左面
                                picRight = pics[1];  //右面
                                picShadow = pics[2];  //阴影
                            }else{
                                pic = layer.get("Pic");
                            }
                            if (!this.pics.containsKey(pic)){
                                //内存中没有图片的时候，先加载一下图片吧
                                this.pics.put(pic,BitmapFactory.decodeFile(sdCard+"/zylWatchFace/"+cName+"/"+pic));
                            }
                            float newX = PosX+this.pics.get(pic).getWidth()/2;
                            float newY = PosY+this.pics.get(pic).getHeight()/2;
                            canvas.translate(newX,newY);
                            float angle=this.mCommonUtils.getMinuteSweepAngle() % 360;
                            canvas.rotate(angle);
                            canvas.translate(-newX,-newY);
                            //看看这里准备画一下阴影试一下
                            if (picShadow!=null){
                                int sPx = 10;  //阴影长(三角形斜边),默认10吧
                                String c_sPx = layer.get("Shadow");  //阴影长度
                                if (c_sPx!=null)
                                    sPx = Integer.parseInt(c_sPx);
                                int sunAngle = 0;  //太阳照射角度
                                String s_sunAngle = layer.get("SunAngle");
                                if (s_sunAngle!=null)
                                    sunAngle = Integer.parseInt(s_sunAngle);
                                double sCon =Math.toRadians(angle-sunAngle);
                                float sX = (float)(Math.sin(sCon)*sPx);  //x坐标
                                float sY = (float)(Math.cos(sCon)*sPx);  //y坐标
                                if (!this.pics.containsKey(picShadow)){
                                    //内存中没有图片的时候，先加载一下图片吧
                                    this.pics.put(picShadow,BitmapFactory.decodeFile(sdCard+"/zylWatchFace/"+cName+"/"+picShadow));
                                }
                                canvas.drawBitmap(this.pics.get(picShadow),PosX+sX, PosY+sY, null);
                                //这里处理指针的左右阴影
                                if(picRight!=null){
                                    if (sunAngle<0){
                                        if(angle>360+sunAngle&&angle<=360||angle>=0&&angle<360+sunAngle-180)
                                            pic = picRight;  //右阴影
                                    }else{
                                        if (angle>sunAngle&&angle<sunAngle+180)
                                            pic = picRight;  //右阴影
                                    }
                                }
                            }
                        }else if (Content.contains("{SecondHand}")){
                            String[] pics = layer.get("Pic").split(",");
                            String picRight=null;
                            String picShadow=null;
                            if (pics.length==2){
                                //这个是有阴影
                                pic = pics[0];   //指针
                                picShadow = pics[1];  //阴影
                            }else if(pics.length>=3){
                                //这个是有阴影，指针还有左右两面
                                pic = pics[0];  //左面
                                picRight = pics[1];  //右面
                                picShadow = pics[2];  //阴影
                            }else{
                                pic = layer.get("Pic");
                            }
                            if (!this.pics.containsKey(pic)){
                                //内存中没有图片的时候，先加载一下图片吧
                                this.pics.put(pic,BitmapFactory.decodeFile(sdCard+"/zylWatchFace/"+cName+"/"+pic));
                            }
                            float newX = PosX+this.pics.get(pic).getWidth()/2;
                            float newY = PosY+this.pics.get(pic).getHeight()/2;
                            canvas.translate(newX,newY);
                            float angle;
                            if (SecondType.equals("run")){
                                angle = this.mCommonUtils.getSecondSweepAngle() % 360;
                            }else{
                                angle = this.mCommonUtils.getSecondWalkAngle() % 360;
                            }
                            canvas.rotate(angle);
                            canvas.translate(-newX,-newY);
                            //看看这里准备画一下阴影试一下
                            if (picShadow!=null){
                                int sPx = 10;  //阴影长(三角形斜边),默认10吧
                                String c_sPx = layer.get("Shadow");  //阴影长度
                                if (c_sPx!=null)
                                    sPx = Integer.parseInt(c_sPx);
                                int sunAngle = 0;  //太阳照射角度
                                String s_sunAngle = layer.get("SunAngle");
                                if (s_sunAngle!=null)
                                    sunAngle = Integer.parseInt(s_sunAngle);
                                double sCon =Math.toRadians(angle-sunAngle);
                                float sX = (float)(Math.sin(sCon)*sPx);  //x坐标
                                float sY = (float)(Math.cos(sCon)*sPx);  //y坐标
                                if (!this.pics.containsKey(picShadow)){
                                    //内存中没有图片的时候，先加载一下图片吧
                                    this.pics.put(picShadow,BitmapFactory.decodeFile(sdCard+"/zylWatchFace/"+cName+"/"+picShadow));
                                }
                                canvas.drawBitmap(this.pics.get(picShadow),PosX+sX, PosY+sY, null);
                                //这里处理指针的左右阴影
                                if(picRight!=null){
                                    if (sunAngle<0){
                                        if(angle>360+sunAngle&&angle<=360||angle>=0&&angle<360+sunAngle-180)
                                            pic = picRight;  //右阴影
                                    }else{
                                        if (angle>sunAngle&&angle<sunAngle+180)
                                            pic = picRight;  //右阴影
                                    }
                                }
                            }
                        }else if (Content.contains("{Switch}")){  //切换
                            String[] pics = layer.get("Pic").split(",");
                            //1帧/秒试一下先
//                      long secondMills = this.mCommonUtils.getSecondsNow()*1000+this.mCommonUtils.getMillsNow();
//                      int y = (int) ((secondMills/(this.INTERVAL_MILLIS*(frameTop-frame+1))) % pics.length);
                            boolean needJump = false;
                            int jumpTop = 0;
                            int jumpIndex = 0;
                            if (frame<frameTop){
                                jumpTop = frameTop / frame;
                                if (this.framesjump.containsKey(i+"")){
                                    jumpIndex = this.framesjump.get(i+"");
                                }
                                if (jumpIndex<jumpTop){
                                    this.framesjump.put(i+"",jumpIndex+1);
                                    needJump = true;
                                }else if (jumpIndex>=jumpTop){
                                    this.framesjump.remove(i+"");
                                }
                            }

                            int z_index = 0;
                            if (this.switchs.containsKey(i+"")){
                                z_index = this.switchs.get(i+"");
                            }
                            if (z_index>=pics.length){
                                z_index = 0;
                            }
                            pic = pics[z_index];
                            if(!needJump) {
                                z_index++;
                            }
                            this.switchs.put(i+"",z_index);
//                      if(z_index == 0){
//                          pic = pics[pics.length-1];
//                      }else{
//                          pic = pics[z_index-1];
//                      }
                        }else if (Content.contains("{Spin}")){  //旋转
                            pic = layer.get("Pic");

                            //这里准备加公转吧
                            if (layer.get("RVLT_X")!=null&&layer.get("RVLT_Y")!=null){
                                if (RVLT_spinAngle==0)
                                    RVLT_spinAngle = 1;
                                boolean RVLT_needJump = false;
                                int RVLT_jumpTop = 0;
                                int RVLT_jumpIndex = 0;
                                if (RVLT_frame<frameTop){
                                    RVLT_jumpTop = frameTop / RVLT_frame;  //跳过几帧要用除
                                    if (this.RVLT_framesjump.containsKey(i+"")){
                                        RVLT_jumpIndex = this.RVLT_framesjump.get(i+"");
                                    }
                                    if (RVLT_jumpIndex<RVLT_jumpTop){
                                        this.RVLT_framesjump.put(i+"",RVLT_jumpIndex+1);
                                        RVLT_needJump = true;
                                    }else if (RVLT_jumpIndex>=RVLT_jumpTop){
                                        this.RVLT_framesjump.remove(i+"");
                                    }
                                }
                                float RVLT_z_spinAngle = 0;
                                if (this.RVLT_spins.containsKey(i+"")){
                                    RVLT_z_spinAngle = this.RVLT_spins.get(i+"");
                                }

                                //加一个往返公转的属性 2018.10.29 by zyl
                                if (RVLT_REP_spinAngle!=0){
                                    int RVLT_z_REP_spinAngle = RVLT_REP_spinAngle;
                                    if (this.RVLT_REP_spins.containsKey(i+"")){
                                        RVLT_z_REP_spinAngle = this.RVLT_REP_spins.get(i+"");
                                    }
                                    if (RVLT_REP_spinAngle<0){  //负角度
                                        if (RVLT_z_REP_spinAngle==RVLT_REP_spinAngle){  //状态是正向旋转的时候
                                            if (RVLT_z_spinAngle<=RVLT_z_REP_spinAngle)
                                                this.RVLT_REP_spins.put(i+"",0);  //设为0表示要往回旋转了
                                        }else if (RVLT_z_REP_spinAngle==0){  //状态是往回旋转了
                                            RVLT_spinAngle = -RVLT_spinAngle;
                                            if (RVLT_z_spinAngle>=RVLT_z_REP_spinAngle)
                                                this.RVLT_REP_spins.put(i+"",RVLT_REP_spinAngle);  //状态设置成正向旋转
                                        }
                                    }else if (RVLT_REP_spinAngle>0){ //正角度
                                        if (RVLT_z_REP_spinAngle==RVLT_REP_spinAngle){  //状态是正向旋转的时候
                                            if (RVLT_z_spinAngle>=RVLT_z_REP_spinAngle)
                                                this.RVLT_REP_spins.put(i+"",0);  //设为0表示要往回旋转了
                                        }else if (RVLT_z_REP_spinAngle==0){  //状态是往回旋转了
                                            RVLT_spinAngle = -RVLT_spinAngle;
                                            if (RVLT_z_spinAngle<=RVLT_z_REP_spinAngle)
                                                this.RVLT_REP_spins.put(i+"",RVLT_REP_spinAngle);  //状态设置成正向旋转
                                        }
                                    }
                                }


                                if(!RVLT_needJump){
                                    RVLT_z_spinAngle = RVLT_z_spinAngle + RVLT_spinAngle;
                                }
                                if (RVLT_z_spinAngle>360||RVLT_z_spinAngle<-360){
                                    RVLT_z_spinAngle = RVLT_z_spinAngle % 360;
                                }
                                this.RVLT_spins.put(i+"",RVLT_z_spinAngle);
                                if (!pics.containsKey(pic)){
                                    //内存中没有图片的时候，先加载一下图片吧
                                    pics.put(pic,BitmapFactory.decodeFile(sdCard+"/zylWatchFace/"+cName+"/"+pic));
                                }
                                float RVLT_X = Float.parseFloat(layer.get("RVLT_X"));
                                float RVLT_Y = Float.parseFloat(layer.get("RVLT_Y"));
                                canvas.translate(RVLT_X,RVLT_Y);
                                canvas.rotate(RVLT_z_spinAngle);  //旋转的角度
                                canvas.translate(-RVLT_X,-RVLT_Y);
//                          canvas.drawBitmap(pics.get(pic),RVLT_X, RVLT_Y, null);  //这里直接画一下试试看吧
                            }

//                            if (spinAngle==0)  //如果旋转角度是0的话，默认就用1吧
//                                spinAngle = 1;
//                      long secondMills = this.mCommonUtils.getSecondsNow()*1000+this.mCommonUtils.getMillsNow();
//                      float y = (int) ((secondMills/(this.INTERVAL_MILLIS*(frameTop-frame+1))) % (360/Math.abs(spinAngle)));
                            boolean needJump = false;
                            int jumpTop = 0;
                            int jumpIndex = 0;
                            if (frame<frameTop){
                                jumpTop = frameTop / frame;  //跳过几帧要用除
                                if (this.framesjump.containsKey(i+"")){
                                    jumpIndex = this.framesjump.get(i+"");
                                }
                                if (jumpIndex<jumpTop){
                                    this.framesjump.put(i+"",jumpIndex+1);
                                    needJump = true;
                                }else if (jumpIndex>=jumpTop){
                                    this.framesjump.remove(i+"");
                                }
                            }


                            float z_spinAngle = 0;
                            if (this.spins.containsKey(i+"")){
                                z_spinAngle = this.spins.get(i+"");
                            }

                            //加一个往返旋转的属性 2018.10.26 by zyl
                            if (REP_spinAngle!=0){
                                int z_REP_spinAngle = REP_spinAngle;
                                if (this.REP_spins.containsKey(i+"")){
                                    z_REP_spinAngle = this.REP_spins.get(i+"");
                                }
                                if (REP_spinAngle<0){  //负角度
                                    if (z_REP_spinAngle==REP_spinAngle){  //状态是正向旋转的时候
                                        if (z_spinAngle<=z_REP_spinAngle)
                                            this.REP_spins.put(i+"",0);  //设为0表示要往回旋转了
                                    }else if (z_REP_spinAngle==0){  //状态是往回旋转了
                                        spinAngle = -spinAngle;
                                        if (z_spinAngle>=z_REP_spinAngle)
                                            this.REP_spins.put(i+"",REP_spinAngle);  //状态设置成正向旋转
                                    }
                                }else if (REP_spinAngle>0){ //正角度
                                    if (z_REP_spinAngle==REP_spinAngle){  //状态是正向旋转的时候
                                        if (z_spinAngle>=z_REP_spinAngle)
                                            this.REP_spins.put(i+"",0);  //设为0表示要往回旋转了
                                    }else if (z_REP_spinAngle==0){  //状态是往回旋转了
                                        spinAngle = -spinAngle;
                                        if (z_spinAngle<=z_REP_spinAngle)
                                            this.REP_spins.put(i+"",REP_spinAngle);  //状态设置成正向旋转
                                    }
                                }
                            }


                            if(!needJump){
                                z_spinAngle = z_spinAngle + spinAngle;
                            }
                            if (z_spinAngle>360||z_spinAngle<-360){
                                z_spinAngle = z_spinAngle % 360;
                            }
                            this.spins.put(i+"",z_spinAngle);
                            if (!pics.containsKey(pic)){
                                //内存中没有图片的时候，先加载一下图片吧
                                pics.put(pic,BitmapFactory.decodeFile(sdCard+"/zylWatchFace/"+cName+"/"+pic));
                            }
                            float newX = PosX+pics.get(pic).getWidth()/2;
                            float newY = PosY+pics.get(pic).getHeight()/2;
                            canvas.translate(newX,newY);
                            canvas.rotate(z_spinAngle);  //旋转的角度
                            canvas.translate(-newX,-newY);
                        }else if (Content.contains("{Week}")){
                            String[] pics = layer.get("Pic").split(",");
                            if(Integer.parseInt(this.mCommonUtils.getDayNameOfWeekNo())>pics.length){
                                pic = pics[pics.length-1];
                            }else{
                                pic = pics[Integer.parseInt(this.mCommonUtils.getDayNameOfWeekNo())-1];
                            }
                            //有切换的图片
                            if (pic.contains("|")){
                                pics = pic.split("\\|");
                                boolean needJump = false;
                                int jumpTop = 0;
                                int jumpIndex = 0;
                                if (frame<frameTop){
                                    jumpTop = frameTop / frame;
                                    if (this.framesjump.containsKey(i+"")){
                                        jumpIndex = this.framesjump.get(i+"");
                                    }
                                    if (jumpIndex<jumpTop){
                                        this.framesjump.put(i+"",jumpIndex+1);
                                        needJump = true;
                                    }else if (jumpIndex>=jumpTop){
                                        this.framesjump.remove(i+"");
                                    }
                                }

                                int z_index = 0;
                                if (this.switchs.containsKey(i+"")){
                                    z_index = this.switchs.get(i+"");
                                }
                                if (z_index>=pics.length){
                                    z_index = 0;
                                }
                                pic = pics[z_index];
                                if(!needJump) {
                                    z_index++;
                                }
                                this.switchs.put(i+"",z_index);
//                          //1帧/秒试一下先
//                          long secondMills = this.mCommonUtils.getSecondsNow()*1000+this.mCommonUtils.getMillsNow();
//                          int y = (int) ((secondMills/(this.INTERVAL_MILLIS*(frameTop-frame+1))) % pics.length);
//                          if(y == 0){
//                              pic = pics[pics.length-1];
//                          }else{
//                              pic = pics[y-1];
//                          }
                            }
                        }else if (Content.contains("{Week.Spin}")){
                            String[] pics = layer.get("Pic").split(",");
                            String picRight=null;
                            String picShadow=null;
                            if (pics.length==2){
                                //这个是有阴影
                                pic = pics[0];   //指针
                                picShadow = pics[1];  //阴影
                            }else if(pics.length>=3){
                                //这个是有阴影，指针还有左右两面
                                pic = pics[0];  //左面
                                picRight = pics[1];  //右面
                                picShadow = pics[2];  //阴影
                            }else{
                                pic = layer.get("Pic");
                            }
                            float angle = spinAngle/7.0f;  //7天
                            float offset=0;
                            if (align.equals("center")){
                                offset = -angle/2;
                            }else if (align.equals("left")){
                                offset = -angle;
                            }
                            if (!this.pics.containsKey(pic)){
                                //内存中没有图片的时候，先加载一下图片吧
                                this.pics.put(pic,BitmapFactory.decodeFile(sdCard+"/zylWatchFace/"+cName+"/"+pic));
                            }
                            float newX = PosX+this.pics.get(pic).getWidth()/2;
                            float newY = PosY+this.pics.get(pic).getHeight()/2;
                            canvas.translate(newX,newY);
                            canvas.rotate(Integer.parseInt(this.mCommonUtils.getDayNameOfWeekNo())*angle+offset);  //旋转的角度
                            canvas.translate(-newX,-newY);
                            //看看这里准备画一下阴影试一下
                            if (picShadow!=null){
                                int sPx = 10;  //阴影长(三角形斜边),默认10吧
                                String c_sPx = layer.get("Shadow");  //阴影长度
                                if (c_sPx!=null)
                                    sPx = Integer.parseInt(c_sPx);
                                int sunAngle = 0;  //太阳照射角度
                                String s_sunAngle = layer.get("SunAngle");
                                if (s_sunAngle!=null)
                                    sunAngle = Integer.parseInt(s_sunAngle);
                                double sCon =Math.toRadians(angle+offset-sunAngle);
                                float sX = (float)(Math.sin(sCon)*sPx);  //x坐标
                                float sY = (float)(Math.cos(sCon)*sPx);  //y坐标
                                if (!this.pics.containsKey(picShadow)){
                                    //内存中没有图片的时候，先加载一下图片吧
                                    this.pics.put(picShadow,BitmapFactory.decodeFile(sdCard+"/zylWatchFace/"+cName+"/"+picShadow));
                                }
                                canvas.drawBitmap(this.pics.get(picShadow),PosX+sX, PosY+sY, null);
                                //这里处理指针的左右阴影
                                if(picRight!=null){
                                    if (sunAngle<0){
                                        if(angle+offset>360+sunAngle&&angle+offset<=360||angle+offset>=0&&angle+offset<360+sunAngle-180)
                                            pic = picRight;  //右阴影
                                    }else{
                                        if (angle+offset>sunAngle&&angle+offset<sunAngle+180)
                                            pic = picRight;  //右阴影
                                    }
                                }
                            }
                        }else if (Content.contains("{Month}")){
                            String[] pics = layer.get("Pic").split(",");
                            if(Integer.parseInt(this.mCommonUtils.getMonthNo())>pics.length){
                                pic = pics[pics.length-1];
                            }else{
                                pic = pics[Integer.parseInt(this.mCommonUtils.getMonthNo())-1];
                            }
                        }else if (Content.contains("{Month.Spin}")){
                            String[] pics = layer.get("Pic").split(",");
                            String picRight=null;
                            String picShadow=null;
                            if (pics.length==2){
                                //这个是有阴影
                                pic = pics[0];   //指针
                                picShadow = pics[1];  //阴影
                            }else if(pics.length>=3){
                                //这个是有阴影，指针还有左右两面
                                pic = pics[0];  //左面
                                picRight = pics[1];  //右面
                                picShadow = pics[2];  //阴影
                            }else{
                                pic = layer.get("Pic");
                            }
                            float angle = spinAngle/12.0f;  //12个月份
                            float offset=0;
                            if (align.equals("center")){
                                offset = -angle/2;
                            }else if (align.equals("left")){
                                offset = -angle;
                            }
                            if (!this.pics.containsKey(pic)){
                                //内存中没有图片的时候，先加载一下图片吧
                                this.pics.put(pic,BitmapFactory.decodeFile(sdCard+"/zylWatchFace/"+cName+"/"+pic));
                            }
                            float newX = PosX+this.pics.get(pic).getWidth()/2;
                            float newY = PosY+this.pics.get(pic).getHeight()/2;
                            canvas.translate(newX,newY);
                            canvas.rotate(Integer.parseInt(this.mCommonUtils.getMonthNo())*angle+offset);  //旋转的角度
                            canvas.translate(-newX,-newY);
                            //看看这里准备画一下阴影试一下
                            if (picShadow!=null){
                                int sPx = 10;  //阴影长(三角形斜边),默认10吧
                                String c_sPx = layer.get("Shadow");  //阴影长度
                                if (c_sPx!=null)
                                    sPx = Integer.parseInt(c_sPx);
                                int sunAngle = 0;  //太阳照射角度
                                String s_sunAngle = layer.get("SunAngle");
                                if (s_sunAngle!=null)
                                    sunAngle = Integer.parseInt(s_sunAngle);
                                double sCon =Math.toRadians(angle+offset-sunAngle);
                                float sX = (float)(Math.sin(sCon)*sPx);  //x坐标
                                float sY = (float)(Math.cos(sCon)*sPx);  //y坐标
                                if (!this.pics.containsKey(picShadow)){
                                    //内存中没有图片的时候，先加载一下图片吧
                                    this.pics.put(picShadow,BitmapFactory.decodeFile(sdCard+"/zylWatchFace/"+cName+"/"+picShadow));
                                }
                                canvas.drawBitmap(this.pics.get(picShadow),PosX+sX, PosY+sY, null);
                                //这里处理指针的左右阴影
                                if(picRight!=null){
                                    if (sunAngle<0){
                                        if(angle+offset>360+sunAngle&&angle+offset<=360||angle+offset>=0&&angle+offset<360+sunAngle-180)
                                            pic = picRight;  //右阴影
                                    }else{
                                        if (angle+offset>sunAngle&&angle+offset<sunAngle+180)
                                            pic = picRight;  //右阴影
                                    }
                                }
                            }
                        }else if (Content.contains("{DayOfMonth}")){
                            String[] pics = layer.get("Pic").split(",");
                            if(Integer.parseInt(this.mCommonUtils.getDayOfMonth())>pics.length){
                                pic = pics[pics.length-1];
                            }else{
                                pic = pics[Integer.parseInt(this.mCommonUtils.getDayOfMonth())-1];
                            }
                        }else if (Content.contains("{DayOfMonth.Spin}")){
                            String[] pics = layer.get("Pic").split(",");
                            String picRight=null;
                            String picShadow=null;
                            if (pics.length==2){
                                //这个是有阴影
                                pic = pics[0];   //指针
                                picShadow = pics[1];  //阴影
                            }else if(pics.length>=3){
                                //这个是有阴影，指针还有左右两面
                                pic = pics[0];  //左面
                                picRight = pics[1];  //右面
                                picShadow = pics[2];  //阴影
                            }else{
                                pic = layer.get("Pic");
                            }
                            float angle = spinAngle/31.0f;  //31天每月份
                            float offset=0;
                            if (align.equals("center")){
                                offset = -angle/2;
                            }else if (align.equals("left")){
                                offset = -angle;
                            }
                            if (!this.pics.containsKey(pic)){
                                //内存中没有图片的时候，先加载一下图片吧
                                this.pics.put(pic,BitmapFactory.decodeFile(sdCard+"/zylWatchFace/"+cName+"/"+pic));
                            }
                            float newX = PosX+this.pics.get(pic).getWidth()/2;
                            float newY = PosY+this.pics.get(pic).getHeight()/2;
                            canvas.translate(newX,newY);
                            canvas.rotate(Integer.parseInt(this.mCommonUtils.getDayOfMonth())*angle+offset);  //旋转的角度
                            canvas.translate(-newX,-newY);
                            //看看这里准备画一下阴影试一下
                            if (picShadow!=null){
                                int sPx = 10;  //阴影长(三角形斜边),默认10吧
                                String c_sPx = layer.get("Shadow");  //阴影长度
                                if (c_sPx!=null)
                                    sPx = Integer.parseInt(c_sPx);
                                int sunAngle = 0;  //太阳照射角度
                                String s_sunAngle = layer.get("SunAngle");
                                if (s_sunAngle!=null)
                                    sunAngle = Integer.parseInt(s_sunAngle);
                                double sCon =Math.toRadians(angle+offset-sunAngle);
                                float sX = (float)(Math.sin(sCon)*sPx);  //x坐标
                                float sY = (float)(Math.cos(sCon)*sPx);  //y坐标
                                if (!this.pics.containsKey(picShadow)){
                                    //内存中没有图片的时候，先加载一下图片吧
                                    this.pics.put(picShadow,BitmapFactory.decodeFile(sdCard+"/zylWatchFace/"+cName+"/"+picShadow));
                                }
                                canvas.drawBitmap(this.pics.get(picShadow),PosX+sX, PosY+sY, null);
                                //这里处理指针的左右阴影
                                if(picRight!=null){
                                    if (sunAngle<0){
                                        if(angle+offset>360+sunAngle&&angle+offset<=360||angle+offset>=0&&angle+offset<360+sunAngle-180)
                                            pic = picRight;  //右阴影
                                    }else{
                                        if (angle+offset>sunAngle&&angle+offset<sunAngle+180)
                                            pic = picRight;  //右阴影
                                    }
                                }
                            }
                        }else if (Content.contains("{DayOfLunarMonth}")){
                            //农历日期
                            LunarCalendar lc = new LunarCalendar(new Date());
                            Calendar cal = Calendar.getInstance();
                            cal.setTime(lc.getDate());
                            String[] pics = layer.get("Pic").split(",");
                            if(cal.get(Calendar.DAY_OF_MONTH)>pics.length){
                                pic = pics[pics.length-1];
                            }else{
                                pic = pics[cal.get(Calendar.DAY_OF_MONTH)-1];
                            }
                        }else if (Content.contains("{DayOfLunarMonth.Spin}")){
                            //农历日期旋转
                            LunarCalendar lc = new LunarCalendar(new Date());
                            Calendar cal = Calendar.getInstance();
                            cal.setTime(lc.getDate());
                            String[] pics = layer.get("Pic").split(",");
                            String picRight=null;
                            String picShadow=null;
                            if (pics.length==2){
                                //这个是有阴影
                                pic = pics[0];   //指针
                                picShadow = pics[1];  //阴影
                            }else if(pics.length>=3){
                                //这个是有阴影，指针还有左右两面
                                pic = pics[0];  //左面
                                picRight = pics[1];  //右面
                                picShadow = pics[2];  //阴影
                            }else{
                                pic = layer.get("Pic");
                            }
                            float angle = spinAngle/30.0f;  //31天每月份
                            float offset=0;
                            if (align.equals("center")){
                                offset = -angle/2;
                            }else if (align.equals("left")){
                                offset = -angle;
                            }
                            if (!this.pics.containsKey(pic)){
                                //内存中没有图片的时候，先加载一下图片吧
                                this.pics.put(pic,BitmapFactory.decodeFile(sdCard+"/zylWatchFace/"+cName+"/"+pic));
                            }
                            float newX = PosX+this.pics.get(pic).getWidth()/2;
                            float newY = PosY+this.pics.get(pic).getHeight()/2;
                            canvas.translate(newX,newY);
                            canvas.rotate(cal.get(Calendar.DAY_OF_MONTH)*angle+offset);  //旋转的角度
                            canvas.translate(-newX,-newY);
                            //看看这里准备画一下阴影试一下
                            if (picShadow!=null){
                                int sPx = 10;  //阴影长(三角形斜边),默认10吧
                                String c_sPx = layer.get("Shadow");  //阴影长度
                                if (c_sPx!=null)
                                    sPx = Integer.parseInt(c_sPx);
                                int sunAngle = 0;  //太阳照射角度
                                String s_sunAngle = layer.get("SunAngle");
                                if (s_sunAngle!=null)
                                    sunAngle = Integer.parseInt(s_sunAngle);
                                double sCon =Math.toRadians(angle+offset-sunAngle);
                                float sX = (float)(Math.sin(sCon)*sPx);  //x坐标
                                float sY = (float)(Math.cos(sCon)*sPx);  //y坐标
                                if (!this.pics.containsKey(picShadow)){
                                    //内存中没有图片的时候，先加载一下图片吧
                                    this.pics.put(picShadow,BitmapFactory.decodeFile(sdCard+"/zylWatchFace/"+cName+"/"+picShadow));
                                }
                                canvas.drawBitmap(this.pics.get(picShadow),PosX+sX, PosY+sY, null);
                                //这里处理指针的左右阴影
                                if(picRight!=null){
                                    if (sunAngle<0){
                                        if(angle+offset>360+sunAngle&&angle+offset<=360||angle+offset>=0&&angle+offset<360+sunAngle-180)
                                            pic = picRight;  //右阴影
                                    }else{
                                        if (angle+offset>sunAngle&&angle+offset<sunAngle+180)
                                            pic = picRight;  //右阴影
                                    }
                                }
                            }
                        }else if (Content.contains("{Battery}")){  //电量图片
                            String[] pics = layer.get("Pic").split(",");
                            if (showBattery100Level>=100){
                                pic = pics[pics.length-1];
                            }else{
                                pic = pics[showBattery100Level/(100/pics.length)];
                            }
                        }else if (Content.contains("{Battery.Spin}")){
                            String[] pics = layer.get("Pic").split(",");
                            String picRight=null;
                            String picShadow=null;
                            if (pics.length==2){
                                //这个是有阴影
                                pic = pics[0];   //指针
                                picShadow = pics[1];  //阴影
                            }else if(pics.length>=3){
                                //这个是有阴影，指针还有左右两面
                                pic = pics[0];  //左面
                                picRight = pics[1];  //右面
                                picShadow = pics[2];  //阴影
                            }else{
                                pic = layer.get("Pic");
                            }
                            float angle = spinAngle/100.0f;  //100的电量
                            float offset=0;
                            if (align.equals("center")){
                                offset = -angle/2;
                            }else if (align.equals("left")){
                                offset = -angle;
                            }
                            if (!this.pics.containsKey(pic)){
                                //内存中没有图片的时候，先加载一下图片吧
                                this.pics.put(pic,BitmapFactory.decodeFile(sdCard+"/zylWatchFace/"+cName+"/"+pic));
                            }
                            float newX = PosX+this.pics.get(pic).getWidth()/2;
                            float newY = PosY+this.pics.get(pic).getHeight()/2;
                            canvas.translate(newX,newY);
                            canvas.rotate(showBattery100Level*angle+offset);  //旋转的角度
                            canvas.translate(-newX,-newY);
                            //看看这里准备画一下阴影试一下
                            if (picShadow!=null){
                                int sPx = 10;  //阴影长(三角形斜边),默认10吧
                                String c_sPx = layer.get("Shadow");  //阴影长度
                                if (c_sPx!=null)
                                    sPx = Integer.parseInt(c_sPx);
                                int sunAngle = 0;  //太阳照射角度
                                String s_sunAngle = layer.get("SunAngle");
                                if (s_sunAngle!=null)
                                    sunAngle = Integer.parseInt(s_sunAngle);
                                double sCon =Math.toRadians(angle+offset-sunAngle);
                                float sX = (float)(Math.sin(sCon)*sPx);  //x坐标
                                float sY = (float)(Math.cos(sCon)*sPx);  //y坐标
                                if (!this.pics.containsKey(picShadow)){
                                    //内存中没有图片的时候，先加载一下图片吧
                                    this.pics.put(picShadow,BitmapFactory.decodeFile(sdCard+"/zylWatchFace/"+cName+"/"+picShadow));
                                }
                                canvas.drawBitmap(this.pics.get(picShadow),PosX+sX, PosY+sY, null);
                                //这里处理指针的左右阴影
                                if(picRight!=null){
                                    if (sunAngle<0){
                                        if(angle+offset>360+sunAngle&&angle+offset<=360||angle+offset>=0&&angle+offset<360+sunAngle-180)
                                            pic = picRight;  //右阴影
                                    }else{
                                        if (angle+offset>sunAngle&&angle+offset<sunAngle+180)
                                            pic = picRight;  //右阴影
                                    }
                                }
                            }
                        }else if(Content.contains("{Battery.Charging}")){
                            //电池充电图标
                            pic = layer.get("Pic");
                            if (!mBCharge)
                                continue;  //没在充电就直接跳过吧
                        }else if (Content.contains("{Step}")){
                            String[] pics = layer.get("Pic").split(",");
                            if (mStep>=10000){
                                pic = pics[pics.length-1];
                            }else{
                                pic = pics[mStep/(10000/pics.length)];
                            }
                        }else if (Content.contains("{Step.Spin}")){
                            String[] pics = layer.get("Pic").split(",");
                            String picRight=null;
                            String picShadow=null;
                            if (pics.length==2){
                                //这个是有阴影
                                pic = pics[0];   //指针
                                picShadow = pics[1];  //阴影
                            }else if(pics.length>=3){
                                //这个是有阴影，指针还有左右两面
                                pic = pics[0];  //左面
                                picRight = pics[1];  //右面
                                picShadow = pics[2];  //阴影
                            }else{
                                pic = layer.get("Pic");
                            }
                            float angle = spinAngle/10000.0f;  //10000的总步数
                            float offset=0;
                            if (align.equals("center")){
                                offset = -angle/2;
                            }else if (align.equals("left")){
                                offset = -angle;
                            }
                            if (!this.pics.containsKey(pic)){
                                //内存中没有图片的时候，先加载一下图片吧
                                this.pics.put(pic,BitmapFactory.decodeFile(sdCard+"/zylWatchFace/"+cName+"/"+pic));
                            }
                            float newX = PosX+this.pics.get(pic).getWidth()/2;
                            float newY = PosY+this.pics.get(pic).getHeight()/2;
                            canvas.translate(newX,newY);
                            canvas.rotate(mStep*angle+offset);  //旋转的角度
                            canvas.translate(-newX,-newY);
                            //看看这里准备画一下阴影试一下
                            if (picShadow!=null){
                                int sPx = 10;  //阴影长(三角形斜边),默认10吧
                                String c_sPx = layer.get("Shadow");  //阴影长度
                                if (c_sPx!=null)
                                    sPx = Integer.parseInt(c_sPx);
                                int sunAngle = 0;  //太阳照射角度
                                String s_sunAngle = layer.get("SunAngle");
                                if (s_sunAngle!=null)
                                    sunAngle = Integer.parseInt(s_sunAngle);
                                double sCon =Math.toRadians(angle+offset-sunAngle);
                                float sX = (float)(Math.sin(sCon)*sPx);  //x坐标
                                float sY = (float)(Math.cos(sCon)*sPx);  //y坐标
                                if (!this.pics.containsKey(picShadow)){
                                    //内存中没有图片的时候，先加载一下图片吧
                                    this.pics.put(picShadow,BitmapFactory.decodeFile(sdCard+"/zylWatchFace/"+cName+"/"+picShadow));
                                }
                                canvas.drawBitmap(this.pics.get(picShadow),PosX+sX, PosY+sY, null);
                                //这里处理指针的左右阴影
                                if(picRight!=null){
                                    if (sunAngle<0){
                                        if(angle+offset>360+sunAngle&&angle+offset<=360||angle+offset>=0&&angle+offset<360+sunAngle-180)
                                            pic = picRight;  //右阴影
                                    }else{
                                        if (angle+offset>sunAngle&&angle+offset<sunAngle+180)
                                            pic = picRight;  //右阴影
                                    }
                                }
                            }
                        }else if (Content.contains("{Weather}")){  //天气
                            pic = layer.get("Pic");
                            String picName = pic.substring(0,pic.indexOf("."));
                            String picEnd = pic.replace(picName,"");
                            pic = picName+mWeatherIndex+picEnd;
                            if (!new File(sdCard+"/zylWatchFace/"+cName+"/"+pic).exists())
                                canDraw = false;
                        }else if (Content.contains("{StopWatch}")){
                            //再来个格式吧
                            String s_format = layer.get("Format");
                            if (s_format==null)
                                s_format = "60s";  //默认等于60秒
                            int minute=-1;
                            int second=-1;
                            if(s_format.contains("m")){
                                minute = Integer.parseInt(s_format.replace("m",""));
                            }else if(s_format.contains("s")){
                                second = Integer.parseInt(s_format.replace("s",""));
                            }
                            //计时器
                            StopWatch stopWatch;
                            //联动-关联同一个计时器
                            String s_refId=layer.get("RefId");
                            if (s_refId!=null){
                                if (stopWatches.containsKey("RefId"+s_refId)){
                                    stopWatch = stopWatches.get("RefId"+s_refId);
                                    if (second!=-1){
                                        stopWatch.setSecond(second);
                                    }
                                    if (minute!=-1){
                                        stopWatch.setMinute(minute);
                                    }
                                }else{
                                    stopWatch = new StopWatch(minute==-1?0:minute,second==-1?0:second);
                                    stopWatches.put("RefId"+s_refId,stopWatch);
                                }
                            }else{
                                if (stopWatches.containsKey("layer_"+i)){
                                    stopWatch = stopWatches.get("layer_"+i);
                                }else{
                                    stopWatch = new StopWatch(minute==-1?0:minute,second==-1?0:second);
                                    stopWatches.put("layer_"+i,stopWatch);
                                }
                            }
                            pic = layer.get("Pic");
                            String s_handType = layer.get("HandType");
                            if (s_handType==null)
                                s_handType = "run";

                            if (!pics.containsKey(pic)){
                                //内存中没有图片的时候，先加载一下图片吧
                                pics.put(pic,BitmapFactory.decodeFile(sdCard+"/zylWatchFace/"+cName+"/"+pic));
                            }
                            float newX = PosX+this.pics.get(pic).getWidth()/2;
                            float newY = PosY+this.pics.get(pic).getHeight()/2;
                            canvas.translate(newX,newY);
                            float angle=0;
                            if (second!=-1){
                                if (s_handType.equals("run")){
                                    angle = stopWatch.getSecondSweepAngle();
                                }else{
                                    angle = stopWatch.getSecondWalkAngle();
                                }
                            }else if (minute!=-1){
                                if (s_handType.equals("run")){
                                    angle = stopWatch.getMinuteSweepAngle();
                                }else{
                                    angle = stopWatch.getMinuteWalkAngle();
                                }
                            }
                            canvas.rotate(angle);
                            canvas.translate(-newX,-newY);
                            //点击的情况
                            String touch = layer.get("Touch");  //默认显示情况
                            boolean swWork = true;  //计时器是否响应点击事件
                            if (touch!=null&&touch.equals("show")){
                                if (pics_hide.contains(i+"")){
                                    swWork = false;
                                }
                            }else if (touch!=null&&touch.equals("hide")){
                                if (!pics_hide.contains(i+"")){
                                    swWork = false;
                                }
                            }
                            String s_touchTime = layer.get("TouchTime");
                            int i_touchTime = 1;
                            if (s_touchTime!=null){
                                i_touchTime = Integer.parseInt(s_touchTime);
                            }
                            if (swWork&&isTouch&&touchTime==i_touchTime){
                                int trX = (int)PosX;
                                int trY = (int)PosY;
                                int trW = this.pics.get(pic).getWidth();
                                int trH = this.pics.get(pic).getHeight();
                                String touchRange = layer.get("TouchRange");  //可以自定义位置
                                if (touchRange!=null){
                                    String[] touchRect = touchRange.split(",");
                                    trX = Integer.parseInt(touchRect[0]);
                                    trY = Integer.parseInt(touchRect[1]);
                                    trW = Integer.parseInt(touchRect[2]);
                                    trH = Integer.parseInt(touchRect[3]);
                                }
                                if (touchX>=trX&&touchX<=trX+trW
                                        &&touchY>=trY&&touchY<=trY+trH){
                                    //这里点击成功了
                                    if (stopWatch.getState()==0)
                                        stopWatch.start();
                                    else if (stopWatch.getState()==1)
                                        stopWatch.stop();
                                    else if (stopWatch.getState()==2)
                                        stopWatch.reset();
                                }
                            }
                        }
                        //这里判断是否显示吧
                        String touch = layer.get("Touch");
                        String touchRange = layer.get("TouchRange");
                        String s_touchTime = layer.get("TouchTime");
                        String s_touchApp = layer.get("TouchApp");  //点击打开app
                        String s_touchAppRange = layer.get("TouchAppRange");
                        int i_touchTime = 1;
                        if (s_touchTime!=null){
                            i_touchTime = Integer.parseInt(s_touchTime);
                        }
                        if (touch!=null&&touchRange!=null&&isTouch&&this.touchTime==i_touchTime){
                            String[] touchRect = touchRange.split(",");
                            int trX = Integer.parseInt(touchRect[0]);
                            int trY = Integer.parseInt(touchRect[1]);
                            int trW = Integer.parseInt(touchRect[2]);
                            int trH = Integer.parseInt(touchRect[3]);
                            if (touchX>=trX&&touchX<=trX+trW
                                    &&touchY>=trY&&touchY<=trY+trH){
                                //如果正好在图片所在范围，那么就触发一下显示/隐藏吧
                                if (touch.equals("show")){
                                    if (!pics_hide.contains(i+"")){
                                        pics_hide.add(i+"");
                                    }else{
                                        pics_hide.remove(i+"");
                                    }
                                }else if (touch.equals("hide")){
                                    if (pics_hide.contains(i+"")){
                                        pics_hide.remove(i+"");
                                    }else{
                                        pics_hide.add(i+"");
                                    }
                                }
                            }
                            //app点击范围分开来吧，默认跟着TouchRange
                            if (s_touchAppRange!=null){
                                touchRect = s_touchAppRange.split(",");
                                trX = Integer.parseInt(touchRect[0]);
                                trY = Integer.parseInt(touchRect[1]);
                                trW = Integer.parseInt(touchRect[2]);
                                trH = Integer.parseInt(touchRect[3]);
                            }
                            if (touchX>=trX&&touchX<=trX+trW
                                    &&touchY>=trY&&touchY<=trY+trH){
                                //如果正好在图片所在范围，那么就触发一下显示/隐藏吧
                                if (touch.equals("show")){
                                    if (!pics_hide.contains(i+"")){
//                                  pics_hide.add(i+"");
                                        //这里显示的时候点击成功了,调用app
                                        if (s_touchApp!=null)
                                            AppTools.startApp(getApplicationContext(),s_touchApp);
                                    }else{
//                                  pics_hide.remove(i+"");
                                    }
                                }else if (touch.equals("hide")){
                                    if (pics_hide.contains(i+"")){
//                                  pics_hide.remove(i+"");
                                    }else{
//                                  pics_hide.add(i+"");
                                        //这里显示的时候点击成功了,调用app
                                        if (s_touchApp!=null)
                                            AppTools.startApp(getApplicationContext(),s_touchApp);
                                    }
                                }else if (touch.equals("all")){  //不做显示隐藏触发
                                    //这里是指显示的时候点击成功了
                                    if (s_touchApp!=null)
                                        AppTools.startApp(getApplicationContext(),s_touchApp);
                                }
                            }
                        }
                        //没有点击的情况处理
                        if (touch!=null&&touch.equals("show")){
                            if (pics_hide.contains(i+"")){
                                canDraw = false;
                            }
                        }else if (touch!=null&&touch.equals("hide")){
                            if (!pics_hide.contains(i+"")){
                                canDraw = false;
                            }
                        }
                        if (canDraw){
                            if (!pics.containsKey(pic)){
                                //内存中没有图片的时候，先加载一下图片吧
                                pics.put(pic,BitmapFactory.decodeFile(sdCard+"/zylWatchFace/"+cName+"/"+pic));
                            }
                            canvas.drawBitmap(pics.get(pic),PosX, PosY, null);
                        }
                    }else{
                        Log.d("zyltest","未知类型的层");
                    }
                    canvas.restore();
                }
                //调试用。。。
//          if (isTouch){
//              this.mPaint.setColor(Color.RED);
//              canvas.drawText(touchTestX+","+touchTestY+"|"+touchTestX1+","+touchTestY1, 1, 200, this.mPaint);
//          }
            }catch (Exception e){
                String content = "";
                if (e_layer!=null){
                    if (e_layer.get("Content")!=null){
                        content = e_layer.get("Content");
                    }
                }
                this.mPaint.setColor(Color.RED);
                this.mPaint.setTypeface(Typeface.DEFAULT);
//                this.mPaint.setTypeface(Typeface.createFromAsset(getApplicationContext().getAssets(), "fonts/fzltqianhei_light.ttf"));
                this.mPaint.setTextSize(12);
                canvas.save();
                canvas.drawText("第"+i+"个层出错", 10, 170, this.mPaint);
                canvas.drawText("Content="+content, 10, 200, this.mPaint);
                canvas.drawText(e.getMessage(), 10, 230, this.mPaint);
                canvas.restore();
//          Toast.makeText(getContext(),"第"+i+"个层出错,Content="+content+","+e.getMessage(),Toast.LENGTH_LONG).show();
                e.printStackTrace();
            }

            if (isTouch){
                isTouch = false;  //直接结束掉
                touchTime = 0;
                touchX = -1;
                touchY = -1;
            }
        }

        @Override
        public void onDraw(Canvas canvas, Rect bounds) {
//            long now = System.currentTimeMillis();
//            mCalendar.setTimeInMillis(now);
//
//            drawBackground(canvas);
//            drawWatchFace(canvas);
            canvas.drawColor(Color.BLACK);  //这个可以解决残影问题...
            this.mCommonUtils.setDrawFilter(canvas);  //抗锯齿设置
            this.mCommonUtils.setTimeToNow();
//            doDayDraw(canvas,"day");  //自定义表盘

            if (mAmbient) {  //mAmbient好像就是dim模式..
                //只画dim层
                doDayDraw(canvas,"dim");
            }else{
                int cHour = Integer.parseInt(this.mCommonUtils.getHourOfString());
                if (DayHour.equals(NightHour)){
                    doDayDraw(canvas,"day");  //白天画图
                }else if (Integer.parseInt(DayHour)<Integer.parseInt(NightHour)){
                    if (cHour>=Integer.parseInt(DayHour)
                            &&cHour<=Integer.parseInt(NightHour)){
                        doDayDraw(canvas,"day");  //白天画图
                    }else{
                        doDayDraw(canvas,"night");  //晚上画图
                    }
                }else if (Integer.parseInt(DayHour)>Integer.parseInt(NightHour)){
                    if (cHour>=Integer.parseInt(NightHour)
                            &&cHour<=Integer.parseInt(DayHour)){
                        doDayDraw(canvas,"night");  //晚上画图

                    }else{
                        doDayDraw(canvas,"day");  //白天画图
                    }
                }
            }
        }


        @Override
        public void onVisibilityChanged(boolean visible) {
            super.onVisibilityChanged(visible);

            if (visible) {
                registerReceiver();
                /* Update time zone in case it changed while we weren't visible. */
//                mCalendar.setTimeZone(TimeZone.getDefault());
                this.mCommonUtils.setTimeToNow();
                invalidate();
            } else {
                unregisterReceiver();
            }

            /* Check and trigger whether or not timer should be running (only in active mode). */
            updateTimer();
        }

        private void registerReceiver() {
            if (mRegisteredTimeZoneReceiver) {
                return;
            }
            mRegisteredTimeZoneReceiver = true;
            IntentFilter filter = new IntentFilter(Intent.ACTION_TIMEZONE_CHANGED);
            MyWatchFace.this.registerReceiver(mTimeZoneReceiver, filter);
        }

        private void unregisterReceiver() {
            if (!mRegisteredTimeZoneReceiver) {
                return;
            }
            mRegisteredTimeZoneReceiver = false;
            MyWatchFace.this.unregisterReceiver(mTimeZoneReceiver);
        }

        /**
         * Starts/stops the {@link #mUpdateTimeHandler} timer based on the state of the watch face.
         */
        private void updateTimer() {
            mUpdateTimeHandler.removeMessages(MSG_UPDATE_TIME);
            if (shouldTimerBeRunning()) {
                mUpdateTimeHandler.sendEmptyMessage(MSG_UPDATE_TIME);
            }
        }

        /**
         * Returns whether the {@link #mUpdateTimeHandler} timer should be running. The timer
         * should only run in active mode.
         */
        private boolean shouldTimerBeRunning() {
            return isVisible() && !mAmbient;
        }

        /**
         * Handle updating the time periodically in interactive mode.
         */
        private void handleUpdateTimeMessage() {
            invalidate();
            if (shouldTimerBeRunning()) {
//                long timeMs = System.currentTimeMillis();
//                long delayMs = INTERACTIVE_UPDATE_RATE_MS
//                        - (timeMs % INTERACTIVE_UPDATE_RATE_MS);
                long delayMs = 1000/frameTop;
                mUpdateTimeHandler.sendEmptyMessageDelayed(MSG_UPDATE_TIME, delayMs);
            }
        }
    }
}
